from fastapi import HTTPException, status
from fastapi.responses import JSONResponse
from models.json_response import JsonData
from typing import Any  # 添加此行



class ApiException(Exception):
    def __init__(
        self, 
        msg: str = "操作失败",
        code: int = -1,
        data: Any = None
    ):
        self.msg = msg
        self.code = code
        self.data = data
        super().__init__(msg)

async def api_exception_handler(request, exc:  Exception)->JSONResponse:
    if isinstance(exc, ApiException):
        response = JsonData.error(msg=exc.msg, code=exc.code)
    elif isinstance(exc, HTTPException):
        response = JsonData.error(msg=exc.detail, code=exc.status_code)
    else: 
        response = JsonData.error(msg=str(exc), code=-1)
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content=response.model_dump()
        )
